package org.osll.tictactoe.transport.udp.server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import org.osll.tictactoe.engine.GameStorageImpl;
import org.osll.tictactoe.game.Game;
import org.osll.tictactoe.transport.DefaultOptions;
import org.osll.tictactoe.transport.tcp.DefaultQuery;
import org.osll.tictactoe.transport.tcp.LoginAcceptedResponse;
import org.osll.tictactoe.transport.tcp.LoginQuery;
import org.osll.tictactoe.transport.tcp.LoginRejectedResponse;
import org.osll.tictactoe.transport.udp.SocketProcessor;

public class LoginServer extends SocketProcessor implements Runnable {

	private DatagramSocket socket = null;
	
	public LoginServer() {
		try {
			socket = new DatagramSocket(DefaultOptions.getInstance().getUdpPort());
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	public void run() {
		for(;;) {
			byte [] buf = new byte[30000];
			DatagramPacket packet = new DatagramPacket(buf,buf.length);
			try {
				socket.receive(packet);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				continue;
			}
			DefaultQuery query = (DefaultQuery)read(packet);
			
			if(query.getType()!=DefaultQuery.Type.LOGIN) {
				write(socket, packet.getSocketAddress(), new LoginRejectedResponse());
			}
			LoginQuery rcq = (LoginQuery)query;
			
			Game c = GameStorageImpl.getInstance().register(rcq.getName(), rcq.getTeam());
			
			LoginAcceptedResponse resp = new LoginAcceptedResponse();
			resp.setPort(c.getTransport().getUdpPort());
			
			write(socket,packet.getSocketAddress(),resp);
		}
	}

}
